package com.awise.app.more.activity;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.awise.R;
import com.awise.base.BaseActivity;
import com.awise.http.RoverGlobal;
import com.awise.util.Constant;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;

import static com.awise.R.id.most_demo;


/**
 * Created by lgz on 2018/1/23.
 */

public class MoreActivity extends BaseActivity implements View.OnClickListener {
    private int  intentDeviceNameCode=100;
    private int  intentControlNumberCode=200;
    private TextView most_device_name_content;
    private TextView most_channel_content;
    private int TEMPERATURE_VISIBLE=0;
    private int TEMPERATURE_GONE=1;
    private int temperature;
    private TextView most_device_date_content;

    private Timer timer;
    private Handler handler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.more_layout);
        temperature=  getIntent().getIntExtra("temperature",TEMPERATURE_VISIBLE);
        LocalBroadcastManager.getInstance(this).registerReceiver(broadcastReceiver, new IntentFilter(Constant.MORE_ACTION));
        initView();
        readTime();
        handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                readName();
            }
        }, 200);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(broadcastReceiver);
        if (timer != null) {
            timer.cancel();
        }
    }

    private void initView() {
        TextView s_back = (TextView) this.findViewById(R.id.tv_back);
        TextView  textView_content = (TextView) this.findViewById(R.id.textView_content);
        textView_content.setText(R.string.more_title);
        s_back.setVisibility(View.VISIBLE);
        s_back.setOnClickListener(this);
        //编辑设备名
        RelativeLayout most_device_name = (RelativeLayout) this.findViewById(R.id.most_device_name);
        ImageView most_device_name_image=  (ImageView) most_device_name.findViewById(R.id.iv_icom_pic);
        most_device_name_image.setImageResource(R.mipmap.edit_name);
        TextView most_device_name_name=  (TextView) most_device_name.findViewById(R.id.most_tv_name);
        most_device_name_name.setText(R.string.device_name);
        most_device_name_content=  (TextView) most_device_name.findViewById(R.id.most_tv_content);
        most_device_name_content.setText("");
        // 因为不能修改名称，这个功能暂时不做
        //most_device_name.setOnClickListener(this);
        //编辑日期时间
        RelativeLayout most_device_date = (RelativeLayout) this.findViewById(R.id.most_device_date);
        ImageView most_device_date_image=  (ImageView) most_device_date.findViewById(R.id.iv_icom_pic);
        most_device_date_image.setImageResource(R.mipmap.current_time);
        TextView most_device_date_name=  (TextView) most_device_date.findViewById(R.id.most_tv_name);
        most_device_date_name.setText(R.string.device_date);
        most_device_date_content=  (TextView) most_device_date.findViewById(R.id.most_tv_content);
/*        try {
            SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String dateStr = dateformat.format(System.currentTimeMillis());
            most_device_date_content.setText(dateStr);
        } catch (Exception e) {
            e.printStackTrace();
        }*/
        //风扇温度控制
        RelativeLayout most_temp = (RelativeLayout) this.findViewById(R.id.most_temp);
        ImageView most_temp_image=  (ImageView) most_temp.findViewById(R.id.iv_icom_pic);
        most_temp_image.setImageResource(R.mipmap.temp_icon);
        TextView most_temp_name=  (TextView) most_temp.findViewById(R.id.most_tv_name);
        most_temp_name.setText(R.string.temperature_function);
        most_temp.setOnClickListener(this);
        if (temperature==TEMPERATURE_VISIBLE){
            most_temp.setVisibility(View.VISIBLE);
        }else {
            most_temp.setVisibility(View.GONE);
        }
        //演示模式
        RelativeLayout most_demo = (RelativeLayout) this.findViewById(R.id.most_demo);
        ImageView most_demo_image=  (ImageView) most_demo.findViewById(R.id.iv_icom_pic);
        most_demo_image.setImageResource(R.mipmap.show_icon);
        TextView most_demo_name=  (TextView) most_demo.findViewById(R.id.most_tv_name);
        most_demo_name.setText(R.string.show_function);
        most_demo.setOnClickListener(this);
        //当前控制路数
        RelativeLayout most_channel = (RelativeLayout) this.findViewById(R.id.most_channel);
        ImageView most_channel_image=  (ImageView) most_channel.findViewById(R.id.iv_icom_pic);
        most_channel_image.setImageResource(R.mipmap.control);
        TextView most_channel_name=  (TextView) most_channel.findViewById(R.id.most_tv_name);
        most_channel_name.setText(R.string.control_number);
        most_channel_content=  (TextView) most_channel.findViewById(R.id.most_tv_content);
//        most_channel_content.setText( getSP(this,"ControlNumber", 1)+"");
        most_channel.setOnClickListener(this);
        //恢复出厂设置
        RelativeLayout most_setting = (RelativeLayout) this.findViewById(R.id.most_setting);
        ImageView most_setting_image=  (ImageView) most_setting.findViewById(R.id.iv_icom_pic);
        most_setting_image.setImageResource(R.mipmap.recorve);
        TextView most_setting_name=  (TextView) most_setting.findViewById(R.id.most_tv_name);
        most_setting_name.setText(R.string.factory_reset);
        most_setting.setOnClickListener(this);
        //关于我们
        RelativeLayout most_about_us = (RelativeLayout) this.findViewById(R.id.most_about_us);
        ImageView most_about_us_image=  (ImageView) most_about_us.findViewById(R.id.iv_icom_pic);
        most_about_us_image.setImageResource(R.mipmap.about_us);
        TextView most_about_us_name=  (TextView) most_about_us.findViewById(R.id.most_tv_name);
        most_about_us_name.setText(R.string.about_us);
        most_about_us.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.tv_back:
                finish();
                break;
            case R.id.most_about_us:
                startActivity(new Intent(this,AboutUsActivity.class));
                break;
            case R.id.most_channel:
                startActivityForResult(new Intent(this,ControlNumberActivity.class),intentControlNumberCode);
                break;
            case R.id.most_setting:
                dialog();
                break;
            case most_demo:
                startActivity(new Intent(this,DemoActivity.class));
                break;
            case R.id.most_temp:
                startActivity(new Intent(this,TempActivity.class));
                break;
            case R.id.most_device_name:
                startActivityForResult(new Intent(this,EditNameActivity.class),intentDeviceNameCode);
                break;
        }
    }

    protected void dialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.factoryreset_msg);
        builder.setTitle(R.string.dialog_title);
        builder.setPositiveButton(R.string.dialog_confirmation, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                reset();
                dialog.dismiss();
            }
        });
        builder.setNegativeButton(R.string.dialog_cannel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        builder.create().show();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        if (requestCode==intentDeviceNameCode&&resultCode==RESULT_OK){
                String name=intent.getExtras().getString("name");
                if (!TextUtils.isEmpty(name)){
                    most_device_name_content.setText(name);
                }
        }else if(requestCode==intentControlNumberCode&&resultCode==RESULT_OK){
            int number=intent.getExtras().getInt("number");
            most_channel_content.setText(number+"");
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        most_channel_content.setText( getSP(this,"ControlNumber", 5)+"");
    }

    public void reset(){
        /*    恢复设置 主机	0xC0 0x0A	0x11	0x01	0x00	0x00	0x00 0x00*/
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00};
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    public void readTime(){
        /*    读取时间 C0 0A 11 01 1a 1f 00 00 15*/
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x1a, 0x1f, 0x00, 0x00, 0x00};
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    public void readName(){
        /*     读取设备名C0 0A 11 01 1A 3B 00 00 31*/
        byte[] bytes = {(byte) 0xc0, 0x0a, 0x11, 0x01, 0x1a, 0x3b, 0x00, 0x00, 0x00};
        bytes[bytes.length - 1] = RoverGlobal.getInstance().getAddValue(bytes, bytes.length);
        RoverGlobal.getInstance().connect.write(bytes);
    }

    StringBuffer  buffers;
    private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent.getAction() == Constant.MORE_ACTION) {
                byte[] buffer = intent.getByteArrayExtra("socket_data");
                if (buffer != null) {
                    byte buffer4 = buffer[4];
                    byte value5 = buffer[5];
                    switch (buffer4) {
                        case 0x20:
//                  //        发送时间 主机	0xC0 0x0A	0x11	0x01	0x20	0x00 0x07	年份(2字节)	月	日	小时		分	秒	星期		x
                       /*     byte[] bytes = {-64, 10, 17, 1, 42, 0, 8, 7, -30, 3, 9, 17, 3, 8, 6, 37};
                            final Calendar c = Calendar.getInstance();
                            TimeZone tz = TimeZone.getDefault();
                            String TimeZoneData = tz.getDisplayName(false, TimeZone.SHORT);
                            c.setTimeZone(TimeZone.getTimeZone(TimeZoneData));
                            byte[] year = new byte[2];//年
                            year[0] = bytes[7];
                            year[1] = (byte) ((bytes[8] < 0 ? (bytes[8] + 256) : bytes[8]) << 8);
                            String year1 = Integer.toHexString(year[0]);
                            String year2 = Integer.toHexString(year[1]);
                            StringBuffer b = new StringBuffer();
                            //        int value8= Integer.parseInt(b.append(year1).append(year2)+"",16);
                            byte value9 = bytes[9];//月
                            byte value10 = bytes[10];//日
                            byte value11 = bytes[11];//时
                            byte value12 = bytes[12];//分
                            byte value13 = bytes[13];//秒
                            byte week = bytes[14];//星期*/
                           /* if(1==week){//星期天
                                week =7;
                            }else if(2==week){//周一
                                week =1;
                            }else if(3==week){//周二
                                week =2;
                            }else if(4==week){//周三
                                week =3;
                            }else if(5==week){//周四
                                week =4;
                            }else if(6==week){//周五
                                week =5;
                            }else if(7==week){//周六
                                week =6;
                            }*/
//                            System.out.println("时间：" +/*value8+*/"年" + value9 + "月" + value10 + "日" + value11 + "时" + value12 + "分" + value13 + "秒");
                            break;
                        case 0x1a:
                            switch (value5) {
                                case 0x1f:
                                    int year1 = buffer[8];
                                    int year2 = buffer[9];
                                    if(year2 < 0) {
                                        year2 += 256;
                                    }
                                    int year = year1 * 256 + year2;

                                    int month = buffer[10];
                                    int day = buffer[11];
                                    int hour = buffer[12];
                                    int minute = buffer[13];
                                    int second = buffer[14];
                                    StringBuilder time = new StringBuilder();
                                    time.append(year);
                                    time.append("-");
                                    time.append(month);
                                    time.append("-");
                                    time.append(day);
                                    time.append(" ");
                                    time.append(hour);
                                    time.append(":");
                                    time.append(minute);
                                    time.append(":");
                                    time.append(second);
                                    final SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                                    try {
                                        Date deviceDate = dateformat.parse(time.toString());
                                        final Calendar calendar = Calendar.getInstance();
                                        calendar.setTime(deviceDate);
                                        timer = new Timer();
                                        timer.schedule(new TimerTask() {
                                            @Override
                                            public void run() {
                                                runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        most_device_date_content.setText(dateformat.format(calendar.getTime()));
                                                        calendar.add(Calendar.SECOND, 1);
                                                    }
                                                });
                                            }
                                        }, 0, 1000);
                                    } catch (ParseException e) {
                                        e.printStackTrace();
                                    }
                                    break;
                                default:
                                    break;
                            }
                            break;
                        default:
                            break;
                    }
                }
            }
        }
    };


}
